<template>
  <Drawer :title="title">
    <BaseForm />
  </Drawer>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'EditDrawer',
});
import { computed, ref, watch } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { querySave, queryUpdate } from '../data/api';
import { drawerFormSchema, handleId, idKey } from '../data/options';
import { message } from 'ant-design-vue';
import { useThrottleFn } from '@vueuse/core';

const emit = defineEmits(['success']);
const title = computed(() => {
  return `${handleId.value ? '编辑' : '新增'}机构`;
});

// 抽屉提交
const onSubmit = useThrottleFn(async (values: Record<string, any>) => {
  console.log(values);
  const { valid } = await formApi.validate();
  if (!valid) return;
  if (!values[idKey.value]) delete values[idKey.value];
  let query = values[idKey.value] ? queryUpdate : querySave;
  let res: any = await query({ ...values, companyType: 2 });
  message.success(res.message);
  onSucClose();
}, 1000);

// 抽屉配置
const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-1/2',
  onCancel() {
    drawerApi.close();
  },
  onConfirm: () => onConfirm(),
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      let data = drawerApi.getData();
      handleId.value = data[idKey.value] || '';
      formApi.setValues({ ...data });
    }
  },
});

// 表单
const [BaseForm, formApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  showDefaultActions: false,
  wrapperClass: 'pl-4 pr-4 pt-4 pb-4',
  schema: drawerFormSchema,
  handleSubmit: onSubmit,
  // 所有表单项
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
});

const onSucClose = () => {
  drawerApi.close();
  emit('success');
};

// 提交按钮
const onConfirm = () => {
  formApi.submitForm();
};
</script>

<style lang="scss" scoped></style>
